package com.huli.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huli.dto.CheckMailDto;
import com.huli.dto.MailDto;
import com.huli.service.IOwnerService;
import com.huli.service.IUserService;
import com.huli.service.MailSenderService;
import com.huli.util.CheckCodeGenerator;
import com.huli.domain.Owner;
import com.huli.domain.User;
import com.huli.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.Duration;
import java.util.Date;

@Service
public class MailSenderServiceImpl implements MailSenderService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOwnerService ownerService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}")
    private String from;


    /**
     * 简单文本邮件
     */
    @Override
    public void sendSimpleMail(MailDto mail) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(mail.getTo());
        //邮件主题
        message.setSubject(mail.getSubject());
        //邮件内容
        message.setText(mail.getContent());
        //发送邮件
        mailSender.send(message);
    }

    /**
     * 发送注册验证邮件
     */
    @Override
    public void sendCheckMail(String to) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        String code = CheckCodeGenerator.checkCodeGenerator(6);
        helper.setTo(to);
        helper.setFrom(from);
        helper.setSubject("邮箱验证码");
        helper.setText("尊敬的用户您好！ \n" +
                "\n" +
                "您的验证码是：" + code + "，请在 5 分钟内进行验证。如果该验证码不为您本人申请，请无视。 ");
        helper.setSentDate(new Date());

        redisTemplate.opsForValue().set(to,code, Duration.ofMinutes(5));

        mailSender.send(mimeMessage);

    }

    /**
     * 1 为用户 2为位主
     *
     * @param checkMailDto
     * @throws MessagingException
     */
    @Override
    public void sendCheckUserMail(CheckMailDto checkMailDto) throws MessagingException {
        JwtUtils jwtUtils = new JwtUtils();
        String token;
        switch (checkMailDto.getType()) {
            case 1: {
                User user = userService.getOne(new QueryWrapper<User>()
                        .eq("user_email", checkMailDto.getTo())
                        .eq("user_account", checkMailDto.getAccount()));

                Assert.notNull(user, "找不到该用户的邮箱");
                token = jwtUtils.generateToken(user.getUserId());
            }
            break;
            case 2: {
                Owner owner = ownerService.getOne(new QueryWrapper<Owner>()
                        .eq("owner_email", checkMailDto.getTo())
                        .eq("owner_account", checkMailDto.getAccount()));

                Assert.notNull(owner, "找不到该用户的邮箱");
                token = jwtUtils.generateToken(owner.getOwnerId());
            }
            break;
            default:
                return;
        }

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setTo(checkMailDto.getTo());
        helper.setFrom(from);
        helper.setSubject("邮箱验证链接");
        helper.setText("尊敬的用户您好！ \n" +
                "\n" +
                "请点击以下链接验证邮箱：" + "http://192.168.10.4:8091/checkMail?token=" + token + "&type=" + checkMailDto.getType() + " ，请在 5 分钟内进行验证。如果该验证码不为您本人申请，请无视。 ");
        helper.setSentDate(new Date());

        mailSender.send(mimeMessage);

    }


}
